package com.mybatis.plus.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;

/**
 * sql准备执行前改变sql
 *
 * ParameterHandler ，StatementHandler，ResultSetHandler
 * @author liuzhiqiang
 */
@Intercepts({
        @Signature(
                type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class, Integer.class}
        )
})
@Slf4j
@Component
public class MyInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取被拦截的对象
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        // 修改 SQL 语句
        String originalSql = statementHandler.getBoundSql().getSql();
        String modifiedSql = modifiedSql(originalSql);
        // 利用反射设置修改后的 SQL
        Field sqlField = BoundSql.class.getDeclaredField("sql");
        sqlField.setAccessible(true);
        sqlField.set(statementHandler.getBoundSql(), modifiedSql);
        // 继续执行后续操作
        return invocation.proceed();
    }

    private String modifiedSql(String originalSql) {
        log.info("originalSql: {}", originalSql);
        return "select 10";
    }
}
